package com.ithao.controller;

import com.ithao.entity.PageResult;
import com.ithao.entity.QueryPageBean;
import com.ithao.entity.Result;
import com.ithao.pojo.Permission;
import com.ithao.pojo.Role;
import com.ithao.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author : ZhangHao
 * @version :1.0
 * @date :Created in 2020/4/2
 * @description : 角色控制器
 */
@RequestMapping("/role")
@RestController
@Slf4j
public class RoleController {
    @Autowired
    private RoleService roleService;

    @GetMapping("findAll")
    public Result findAll() {
        List<Role> roleList = roleService.findAll();
        log.info("[查询所有角色] roleList:{}", roleList);
        return new Result(true, "查询成功", roleList);
    }

    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/findPage")
    public Result findPage(@RequestBody QueryPageBean queryPageBean) {
        if (queryPageBean == null) {
            queryPageBean = new QueryPageBean();
            queryPageBean.setCurrentPage(1);
            queryPageBean.setPageSize(10);
        }
        log.info("[角色-分页查询]data:{}", queryPageBean);
        PageResult pageResult = roleService.findPage(queryPageBean);

        return new Result(true, "查询成功", pageResult);
    }

    /**
     * 添加
     *
     * @param role
     * @param permissionIds
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Role role, Integer[] permissionIds) {
        log.info("[角色-添加]data:{},permissionId:{}", role, permissionIds);
        roleService.add(role, permissionIds);
        return new Result(true, "添加成功");
    }

    @GetMapping("/findById")
    public Result findById(@RequestParam("id") Integer id) {
        log.info("[角色]data:{}", id);
        Role role = roleService.findById(id);

        return new Result(true, "查找成功", role);
    }

    /**
     * 根据角色Id查询角色的所有权限
     *
     * @param id
     * @return
     */
    @GetMapping("/findPermissionIdByRoleId")
    public Result findPermissionIdByRoleId(@RequestParam("id") Integer id) {
        log.info("[角色]-根据角色ID查询权限data:{}", id);
        List<Permission> permissionList = roleService.findPermissionByRole(id);
        return new Result(true, "查找成功", permissionList);
    }

    @PostMapping("/update")
    public Result update(@RequestBody Role role, Integer[] permissionIds) {
        log.info("[角色]-编辑data:{},permissionIds:{}", role, permissionIds);
        roleService.update(role, permissionIds);
        return new Result(true, "更新成功");
    }

    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Integer id) {
        log.info("[权限-删除]data:{}", id);
        roleService.delete(id);
        return new Result(true,"删除成功");
    }
}
